<?php

namespace app\api\controller;

use think\Controller;
use think\Request;
use think\Validate;
use app\util\Utils;
use think\Db;
use app\admin\model\Code;
use app\api\model\Item;
use app\api\model\ItemImg;
use app\api\model\ItemProcess;
use think\Cache;
use think\Log;

class SkinController extends Controller {
    /*
     * 小程序拍照测肤调用的接口
     */

    /*
     * code列表
     */
    

    public function code() {
        /*
         * 0  成功
         * 1  参数错误
         * 2  验证失败
         * 3  请求黑名单
         * 4  token无效
         * 1001  令牌授权错误
         * 8001  请求参数错误
         * 9999  其它错误
         * 
         * 2002  没有发现此项目  
         * 2003  此项目已经下架 
         * 2004  
         * 2005  
         */
    }
    //appid
    const APPID = '31476';

    //商户号
    const appSecret = '46cb70d61e34437ba24e2a99b89b5cf7';
    /*
     * 返回数据
     */

    public static function ajaxReturn($code, $msg, $data) {
        $return = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ];

        return $return;
    }
    
    /*
     * 获取access Token
     */
    public function getAccessToken(){
        $app_production = config('clifeconfig.app_production');
        if($app_production){
            $tokenPath = config('clifeconfig.OpenToken');
        }  else {
            $tokenPath = config('clifeconfig.ItestToken');
        }
//        $appId = config('clifeconfig.appid');
//        $appSecret = config('clifeconfig.appSecret');
        $appId = self::APPID;
        $appSecret = self::appSecret;
        $url = $tokenPath.'?appId='.$appId.'&appSecret='.$appSecret.'&timestamp='.time()*1000;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        curl_close($ch);
        $result = json_decode($result,TRUE);
        $result = $result['data']['accessToken'];
        return $result;
    }
    
    /*
     * 生成签名
     * $array 必须包含accessToken
     * 将请求方法+请求地址+所有参数按照参数名的字母顺序升序排序后拼接+appSecret 
     * 将第1步的结果MD5后生成签名参数sign。（签名后的MD5需要转换成小写）
     * 
     * 请求方法为GET或POST，注意大写。 
     * 请求地址为客户端请求完整地址，如：http://open.api.clife.cn/v1/data/get 
     * 参数拼接，按照参数名的字母顺序升序排序后进行拼接，如：accessToken=xxx&appId=xxx&name1=value1&name2=value2& 
     * 组成完整的拼接，如：GEThttp://open.api.clife.cn/v1/data/getaccessToken=xxx&appId=xxx&name1=value1&name2=value2&appSecret 
     * 生成MD5值，如：74b024f42f3075c4c06e4e8f22ca7a5f
     */

    public function sign($url,$method,$array) {
//        $array = array_merge($array, $token);
        ksort($array);
        $string = "";
        while (list($key, $val) = each($array)) {
            $string = $string . $key . '=' . $val . '&';
        }
        $string = substr($string, 0, strlen($string) - 1);
        $appSecret = self::appSecret;
        $string = $method.$url.$string.'&'.$appSecret;
//        return $string;
        return md5($string);
    }
    
    public function ces(){
        $url = 'http://www.baidu.com';
        $method = 'POST';
        $array = ['a'=>666,'b'=>999];
        return $this->sign($url, $method, $array);
    }
    
   /*
     * 拍照测肤
     * 作者 xfwed
     * 日期 2021-09-29
     *
     */

    public function skinAnalysis() {
        $rule = [
            'openId' => 'require',
            'phone' => 'require',
            'picUrl' => 'require',
        ];
        $msg = [
            'openId.require' => 'openid必须',
            'phone.require' => '手机号必须',
            'picUrl.require' => '图片必须',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return $this->ajaxReturn(1, $error, null);
        }

        $openId = $all['openId'];  
        $phone = $all['phone'];
        $picUrl = $all['picUrl'];
        $ctmRow = Db::name('custom')
                ->where('custom_phone',$phone)
                ->where('status',2)
                ->where('smallshop_type',0)
                ->field('id,custom_name,custom_photo,sex,birthday')
                ->find();
        
        $app_production = config('clifeconfig.app_production');
        if($app_production){
            $apiPath = config('clifeconfig.OpenApiPath');
        }  else {
            $apiPath = config('clifeconfig.ItestApiPath');
        }
        $url = $apiPath.'open/skinAnalysis';
        $method = 'POST';
        
        $data['appId'] = self::APPID;
        $data['accessToken'] = $this->getAccessToken();
        $data['timestamp'] = time()*1000;
        $customerInfo['openId'] = $openId;
        $customerInfo['userName'] = $ctmRow['custom_name'];
        $customerInfo['phone'] = $phone;
        $customerInfo['headimgUrl'] = $ctmRow['custom_photo'];
        $customerInfo['sex'] = $ctmRow['sex'];
        $customerInfo['birthday'] = $ctmRow['birthday'];
        $customerInfo['province'] = '';
        $customerInfo['city'] = '';
        $customerInfo['picUrl'] = $picUrl;
        $storeId = Db::name('store_ctm')->where('ctm_id',$ctmRow['id'])->value('store_id');
        if(empty($storeId)){
            $storeId = 46;
        }
        $customerInfo['storeId'] = $storeId;
        $data['customerInfo'] = json_encode($customerInfo);
        $data['sign'] = $this->sign($url, $method, $data);
//        print_r($data);
        $result = Utils::curlPost1($url,$data);
        $result = json_decode($result,true);
//        print_r($result);die;
        //return $this->ajaxReturn(0, '测肤成功', 'https://cms.clife.cn/manages/mobile/cBeauty/beautyReportKKM/index.html?openId=oxSpt5SdlbbZ6kIfB81GGpdSwi2o&photographId=109977&account=18226916666&share=1#/skinTestReport/analysis');
        if($result['code'] == 0){
            //根据手机号和店铺id 找用户id
            $customRow = Db::name('custom')
                    ->where('custom_phone', '=', $result['data']['phone'])
                    ->where('status',2)
                    ->where('smallshop_type',0)
                    ->field('id')
                    ->find();
            if(empty($customRow)){
                $customRow['id'] = 0;
            }
            $ctm_id = $customRow['id'];
            $het_data['phone'] = $result['data']['phone'];
            $het_data['mmid'] = '';
            $het_data['ctm_id'] = $ctm_id;
            $het_data['csdata'] = $result['data']['skindata'];
            $het_data['type'] = 1;
            $het_data['h5url'] = $result['data']['h5url'];
            $het_data['score'] = $result['data']['totalScore'];
            $het_data['add_time'] = date('Y-m-d H:i:s');
            $het_data['cs_from'] = 2;
            Db::name('het_data')->insert($het_data);
            return $this->ajaxReturn(0, '测肤成功', $result['data']['h5url']);
        }  else {
            Log::info($phone.'拍照测肤失败'.$result['code'].'--------'.$result['msg']);
            return $this->ajaxReturn($result['code'],'没有检测到正面人脸，调整距离，正对镜头再拍一次吧', $result['msg']);
        }
    }

}

?>